<template>
  <div class="main">
    <el-row :gutter="20" style="margin-bottom: 10px">
      <el-col :span="6" style="display:flex;align-items: center">
        <p class="label-form"> 审核级别：</p>
        <el-radio-group @input="changeForm" v-model="isAudit" style="margin-top: 10px;margin-left: 30px">
          <el-radio :label="0">无审核</el-radio>
          <el-radio :label="1">商铺审核</el-radio>
        </el-radio-group>
      </el-col>

    </el-row>
    <el-row :gutter="24">
      <el-col :span="3">
        <p class="label-form"> 商铺名称：</p>
        <el-input v-model="queryParams.name" placeholder="请输入商铺名称"></el-input>
      </el-col>
      <el-col :span="3">
        <p class="label-form"> 手机号：</p>
        <el-input v-model="queryParams.phone" placeholder="请输入商铺名称"></el-input>
      </el-col>
      <el-col :span="4">
        <p class="label-form"> 状态：</p>
        <el-select style="width: 100%;" clearable v-model="queryParams.status" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <p class="label-form"> 时间：</p>
        <el-date-picker
          clearable
          v-model="createTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-col>
      <el-col :span="4" style="margin-left: 150px">
        <p class="label-form"></p>
        <el-button type="primary" @click="getSelect" icon="el-icon-search">搜索</el-button>
        <el-button type="warning" @click="resert" icon="el-icon-refresh-right">重置</el-button>
      </el-col>
    </el-row>


    <el-row  element-loading-text="正在导出中"
             v-loading="loading"
             :gutter="20" style="margin-top: 10px">
      <el-col :span="4">
        <el-button @click="addShop" type="primary" icon="el-icon-plus">新增</el-button>
        <el-button @click="downloadForm" type="primary" icon="el-icon-download">导出</el-button>
      </el-col>

    </el-row>

    <el-table :data="tableData" max-height="800" border style="margin-top: 30px">
      <el-table-column prop="name" min-width="200" label="商铺名称"></el-table-column>
      <el-table-column prop="phone" width="200"  label="联系方式 "></el-table-column>
      <el-table-column prop="address" min-width="200"  label="店铺地址"></el-table-column>
<!--      <el-table-column prop="payType" min-width="200"  label="店铺具体位置">-->
<!--        <template slot-scope="scope">-->
<!--          {{ scope.row.longitude }} / {{ scope.row.latitude }}-->
<!--          <el-button type="primary" size="mini">查看</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="cover" min-width="200"  label="店铺照片">
        <template slot-scope="scope">
          <el-image  style="width: 50px; height: 50px" :src="scope.row.cover" :preview-src-list="[scope.row.cover]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="cover" min-width="200"  label="营业执照">
        <template slot-scope="scope">
          <el-image  style="width: 50px; height: 50px" :src="scope.row.license" :preview-src-list="[scope.row.license]"></el-image>
        </template>
      </el-table-column>
<!--      <el-table-column prop="tyre" width="210"  label="轮胎品牌">-->
<!--        <template slot-scope="scope">-->
<!--          支持的轮胎：{{scope.row.tyre}}-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column min-width="200"  label="开启时间">-->
<!--        <template slot-scope="scope">-->
<!--          {{ parseTime(scope.row.opentime) }}-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column min-width="200"  label="关闭时间">-->
<!--        <template slot-scope="scope">-->
<!--          {{ parseTime(scope.row.closetime) }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column min-width="150"  prop="status" label="店铺状态">
        <template slot-scope="scope">
          {{ status(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column min-width="150"  prop="status" label="创建时间">
        <template slot-scope="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="300" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="updateShop(scope.row)">修改</el-button>
          <el-button type="primary" size="mini" icon="el-icon-view" @click="viewShop(scope.row)">查看</el-button>
          <el-button size="mini" type="danger" @click="deleteShop(scope.row)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="isEdit ? '修改-用户店铺':'用户店铺'"
      :visible.sync="dialogVisible"
      width="900px"
      :before-close="handleClose">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="商铺名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
<!--        <el-form-item label="轮胎品牌">-->
<!--          <el-select-->
<!--            style="width: 100%;"-->
<!--            v-model="form.brand"-->
<!--            multiple-->
<!--            clearable-->
<!--            placeholder="请选择轮胎">-->
<!--            <el-option-->
<!--              v-for="item in optionsBrand"-->
<!--              :key="item.id"-->
<!--              :label="item.name"-->
<!--              :value="item.id">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="店铺照片">
          <lz-upload :limit="1" :img-src="form.cover" @uploadImage="uploadImage"></lz-upload>
<!--          <image-upload :limit="1" :isShowTip="false" v-model="form.cover"></image-upload>-->
        </el-form-item>
        <el-form-item label="营业执照">
          <lz-upload :limit="1" :img-src="form.license" @uploadImage="uploadImage1"></lz-upload>
          <!--          <image-upload :limit="1" :isShowTip="false" v-model="form.cover"></image-upload>-->
        </el-form-item>
        <el-form-item label="店铺地址">
          <baidu-map
            @click="setMark"
            class="map"
            style="display: flex; flex-direction: column"
            :center="center"
            :zoom="15"
            :scroll-wheel-zoom="false">
            <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
            <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
            <bm-marker
              :position="mark"
              :dragging="true" animation="BMAP_ANIMATION_BOUNCE">
              <bm-label
                :content="content"
                :labelStyle="{color: 'red', fontSize : '12px'}"
                :offset="{width: -35, height: 30}"/>
            </bm-marker>
            <bm-local-search :keyword="keyword" :auto-viewport="true" :location="location"></bm-local-search>
          </baidu-map>
        </el-form-item>
        <el-form-item label="具体位置">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
<!--        <el-form-item label="开启时间">-->
<!--          <el-time-picker v-model="form.opentime" type="datetime" placeholder="选择日期时间"></el-time-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="关闭时间">-->
<!--          <el-time-picker v-model="form.closetime" type="datetime" placeholder="选择日期时间"></el-time-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="用户状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1" >启用</el-radio>
            <el-radio :label="0" >禁用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="isEdit || isAdd" @click="cancel">取消</el-button>
        <el-button v-if="isEdit && !isAdd" type="primary" @click="updateForm">立即修改</el-button>
        <el-button v-if="!isEdit && isAdd" type="primary" @click="submitAdd">提交</el-button>
        <el-button v-if="!isEdit && !isAdd" type="primary" @click="cancel">关闭</el-button>
      </span>
    </el-dialog>


    <div class="box-pager">
      <pagination
        v-show="pager.total>0"
        :total="pager.total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getListsPage"
      />

    </div>
    <div class="safe"></div>
  </div>
</template>

<script>
import {parseTime} from "@/utils/ruoyi";
import axios from "axios";
import {
  deleteStore, exportInstallList, exportStoreList, getAuditForm,
  getStoreArray,
  getStoreList,
  getTyreList,
  getUserList,
  insertShop, updateAuditForm,
  updateShopStore
} from '@/api/apiFox'
import { streamFileDownload1 } from '@/utils'

export default {
  data() {
    return {
      currentPage1: 5,
      value1: '',
      isAudit:1,
      pager:{
        total:100
      },
      loading:false,
      form: {},
      dialogVisible: false,
      isEdit: false,
      isAdd:false,
      center: {lng: 117.404, lat: 35.915},
      mark: {lng: '', lat: ''},
      content:"",
      location: '',
      keyword: '',
      tableData: [],
      createTime:[],
      options: [
        {value: 0, label: '全部'},
        {value: 1, label: '禁用'},
        {value: 2, label: '启用'},
      ],
      optionsBrand:[],
      queryParams:{
        pageNum:1,
        pageSize:10,
        name:"",
        phone:"",
        status:""
      }
    }
  },
  watch:{
    createTime(newValue,oldValue){
      console.log(newValue)
      if (newValue && newValue.length>0){
        this.queryParams.beginTime = parseTime(newValue[0])
        this.queryParams.endTime = parseTime(newValue[1])
      }else{
        this.queryParams.beginTime = null
        this.queryParams.endTime =null
      }
    }
  },
  mounted() {
    this.getAudit()
    this.getLists(this.queryParams)
  },
  created() {
    this.getBaseInfo()
  },
  methods: {
    downloadForm(){
      this.$prompt('请输入导出文件名', '文件导出', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }) .then(({ value }) => {
        this.loading=true
        exportStoreList(this.queryParams).then(res=>{
          streamFileDownload1(res, `${value}.xlsx`)
          this.loading=false
          this.$message.success('导出成功')
        }).catch(err=>{
          this.loading=false
          this.$message.error('导出失败')
        })
        // console.log(file,1111)

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },


    changeForm(e){
      console.log(e)
      updateAuditForm({type:2}).then(res=>{
        this.$message.success('操作成功')
        this.isAudit = e

      })
    },
    getAudit(){
      getAuditForm(2).then(res=>{
        console.log(res)
        if(res.data){
          this.isAudit =0
        }else{
          this.isAudit = 1
        }
      })
    },

    getSelect(){
      this.getLists(this.queryParams)
    },

    cancel(){
      this.form={}
      this.isAdd=false
      this.isEdit=false
      this.getLists(this.queryParams)
      this.getAudit()
      this.mark = {lng: "", lat: ""}
      this.center ={lng: "", lat: ""}
      this.dialogVisible=false
    },

    resert(){
      this.queryParams={
        pageNum:1,
        pageSize:10,
        name:"",
        phone:"",
        status:""
      }
      this.getLists(this.queryParams)
    },
    getBaseInfo(){
      getTyreList().then(res=>{
        this.optionsBrand = res
      })
      getStoreList().then(res=>{
        this.optionsStore = res
      })

    },
    parseTime,
    getListsPage(e){
      this.queryParams.pageNum = e.page
      this.queryParams.pageSize = e.limit
      this.getLists(this.queryParams)
    },
    getLists(params) {
      getStoreArray(params).then(res=>{
        console.log(res)
        this.pager.total=res.total
        this.tableData =res.rows
      })
    },

    uploadImage(e){
      this.form.cover = e
    },
    uploadImage1(e){
      this.form.license = e
    },

    submitAdd(){
      console.log(this.form)
      if (!this.form.name){
        this.$message.error('商铺名称必填')
        return
      }
      if (!this.form.phone){
        this.$message.error('联系方式必填')
        return
      }
      if (!this.form.address){
        this.$message.error('店铺地址必填')
        return
      }
      if (!this.form.cover){
        this.$message.error('店铺照片必填')
        return
      }
      if (!this.form.latitude){
        this.$message.error('请选择位置')
        return
      }
      // if (!this.form.opentime){
      //   this.$message.error('开启时间必填')
      //   return
      // }
      // if (!this.form.closetime){
      //   this.$message.error('关闭时间必填')
      //   return
      // }
      insertShop(this.form).then(res=>{
        this.$message.success('新增成功')
        this.cancel()
      })
    },

    updateForm(){
      updateShopStore(this.form).then(res=>{
        this.$message.success('修改成功')
        this.cancel()
      })
    },

    setMark(e) {
      console.log(e)
      this.mark = {lng: e.point.lng, lat: e.point.lat}
      this.form.latitude = e.point.lat
      this.form.longitude = e.point.lng
      this.reverseGeocode(e.point.lat,e.point.lng)
    },
    updateShop(item) {
      console.log(item)
      this.dialogVisible = true
      this.form = item
      this.mark = {lng: item.longitude, lat: item.latitude}
      this.center = {lng: item.longitude, lat: item.latitude}
      this.isEdit = true
    },
    viewShop(item) {
      this.dialogVisible = true
      this.form = item
      this.mark = {lng: item.longitude, lat: item.latitude}
      this.center = {lng: item.longitude, lat: item.latitude}
      this.isEdit = false
    },
    addShop() {
      this.dialogVisible = true
      this.form = {}
      this.form.status = 1
      this.form.cover = ""
      this.mark = {lng: "", lat: ""}
      this.center ={lng: "", lat: ""}
      this.isEdit = false
      this.isAdd=true
    },

    deleteShop(item){
      // this.$message.warning('功能维护中，暂时无法删除')
      updateShopStore({id:item.id,isdelete:1}).then(res=>{
        this.$message.success('删除成功')
        this.getLists(this.queryParams)
      })
    },


    reverseGeocode(lat, lon) {
      axios({method:'get',url:"https://api.map.baidu.com/reverse_geocoding/v3",params:{
          ak:"gDrnUUVv8eC1ryse6GX9wQ3r7XXv8CaN",
          extensions_poi:1,
          output:"json",
          location:`${lat},${lon}`
        }}).then(res=>{
        console.log(res.data.result)
        this.form.address =res.data.result.formatted_address_poi
        this.form.province = res.data.result.addressComponent.province
        this.form.city = res.data.result.addressComponent.city
      }).catch(err=>{
        console.log(err)
      })


      axios(`https://api.map.baidu.com/reverse_geocoding/v3`)
        .then(data => {
          console.log(data.data.address);
          this.content =
            data.data.address.state + '-'+data.data.address.city
          this.form.address = this.content
        })
        .catch(error => console.error('Error:', error));
    },
    handleClose() {
      this.dialogVisible = false
    },
    status(val) {
      switch (val) {
        case 0: {
          return '禁用'
        }
        case 1: {
          return '启用'
        }
      }
    }
  },
}
</script>


<style scoped lang="scss">
.map {
  width: 100%;
  height: 300px;
}

.main {
  width: 100%;
  min-height: 100vh;
  padding: 30px;
  box-sizing: border-box;

  .label {
    font-size: 14px;
    height: 20px;
    margin-bottom: 5px;
  }
}

.grid-content {
  height: 40px;
  text-align: right;
  line-height: 40px;
}

.bg-purple {
  font-size: 14px;
  color: #3f3f3f;
}
</style>
